// ==================== 配置数据 ====================
// 【待填充】在这里修改你的打字机文案
const typewriterTexts = [
    '全栈开发工程师 💻',
    'UI/UX 设计师 🎨',
    '产品经理 📱',
    '创意工作者 ✨'
];

// 【待填充】个人信息（用于生成 vCard）
const personalInfo = {
    name: '你的名字',
    title: '全栈开发工程师',
    email: 'your.email@example.com',
    phone: '+86 138 0000 0000',
    location: '北京，中国',
    website: 'https://yourwebsite.com',
    github: 'https://github.com/yourusername',
    linkedin: 'https://linkedin.com/in/yourusername'
};

// ==================== 主题切换 ====================
const themeToggle = document.getElementById('themeToggle');
const body = document.body;

// 从本地存储加载主题
const currentTheme = localStorage.getItem('theme') || 'light';
body.setAttribute('data-theme', currentTheme);
updateThemeIcon(currentTheme);

themeToggle.addEventListener('click', () => {
    const theme = body.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
    
    // 直接切换主题，CSS 会自动处理渐变过渡
    body.setAttribute('data-theme', theme);
    localStorage.setItem('theme', theme);
    updateThemeIcon(theme);
    
    // 添加丝滑的切换动画
    themeToggle.style.transform = 'scale(0.9) rotate(180deg)';
    setTimeout(() => {
        themeToggle.style.transform = '';
    }, 400);
    
    // 主题切换动效：背景波纹扩散
    createThemeTransitionEffect();
});

function updateThemeIcon(theme) {
    const icon = themeToggle.querySelector('i');
    if (theme === 'dark') {
        icon.className = 'fas fa-sun';
    } else {
        icon.className = 'fas fa-moon';
    }
}

// 主题切换动效
function createThemeTransitionEffect() {
    // 创建波纹扩散效果
    const ripple = document.createElement('div');
    ripple.className = 'theme-ripple';
    
    // 从主题按钮位置开始
    const rect = themeToggle.getBoundingClientRect();
    ripple.style.left = rect.left + rect.width / 2 + 'px';
    ripple.style.top = rect.top + rect.height / 2 + 'px';
    
    document.body.appendChild(ripple);
    
    // 动画结束后移除
    setTimeout(() => {
        ripple.remove();
    }, 800);
}

// ==================== 鸟群算法粒子背景 ====================
const canvas = document.getElementById('particleCanvas');
const ctx = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// 鼠标位置
const mouse = {
    x: null,
    y: null,
    radius: 150
};

window.addEventListener('mousemove', (e) => {
    mouse.x = e.x;
    mouse.y = e.y;
});

window.addEventListener('mouseleave', () => {
    mouse.x = null;
    mouse.y = null;
});

// 生成 "LHC" 文字的目标点
function generateTextPoints() {
    const points = [];
    const tempCanvas = document.createElement('canvas');
    const tempCtx = tempCanvas.getContext('2d');
    
    // 增大画布尺寸，让LHC更大
    tempCanvas.width = 900;
    tempCanvas.height = 300;
    
    tempCtx.fillStyle = 'white';
    tempCtx.font = 'bold 200px Arial';
    tempCtx.textAlign = 'center';
    tempCtx.textBaseline = 'middle';
    tempCtx.fillText('LHC', tempCanvas.width / 2, tempCanvas.height / 2);
    
    const imageData = tempCtx.getImageData(0, 0, tempCanvas.width, tempCanvas.height);
    const data = imageData.data;
    
    // LHC固定在右侧，距离右边界150px
    const rightMargin = 150;
    const lhcRightBoundary = canvas.width - rightMargin;
    const lhcLeftStart = lhcRightBoundary - tempCanvas.width;
    
    // 提取像素点，稀疏采样
    for (let y = 0; y < tempCanvas.height; y += 4) {
        for (let x = 0; x < tempCanvas.width; x += 4) {
            const index = (y * tempCanvas.width + x) * 4;
            const alpha = data[index + 3];
            
            if (alpha > 128) {
                // LHC固定在右侧：从右边界-右边距-LHC宽度开始
                const px = lhcLeftStart + x;
                const py = (canvas.height - tempCanvas.height) / 2 + y;
                points.push({ x: px, y: py });
            }
        }
    }
    
    return points;
}

const textPoints = generateTextPoints();

// 粒子类（鸟群算法）
class Boid {
    constructor(targetPoint) {
        this.x = Math.random() * canvas.width;
        this.y = Math.random() * canvas.height;
        this.vx = Math.random() * 2 - 1;
        this.vy = Math.random() * 2 - 1;
        this.target = targetPoint;
        this.size = Math.random() * 2 + 1.5;
        this.opacity = Math.random() * 0.5 + 0.5;
        this.maxSpeed = 2;
        this.maxForce = 0.05;
    }

    // 鸟群算法 - 寻找目标
    seek(target) {
        const desired = {
            x: target.x - this.x,
            y: target.y - this.y
        };
        
        const distance = Math.sqrt(desired.x * desired.x + desired.y * desired.y);
        
        if (distance > 0) {
            desired.x = (desired.x / distance) * this.maxSpeed;
            desired.y = (desired.y / distance) * this.maxSpeed;
        }
        
        const steer = {
            x: desired.x - this.vx,
            y: desired.y - this.vy
        };
        
        // 限制转向力
        const steerMag = Math.sqrt(steer.x * steer.x + steer.y * steer.y);
        if (steerMag > this.maxForce) {
            steer.x = (steer.x / steerMag) * this.maxForce;
            steer.y = (steer.y / steerMag) * this.maxForce;
        }
        
        return steer;
    }

    // 鼠标排斥
    flee(target) {
        const dx = this.x - target.x;
        const dy = this.y - target.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance < mouse.radius && distance > 0) {
            const force = {
                x: (dx / distance) * this.maxSpeed * 2,
                y: (dy / distance) * this.maxSpeed * 2
            };
            
            // 根据距离调整力度
            const strength = 1 - distance / mouse.radius;
            force.x *= strength;
            force.y *= strength;
            
            return force;
        }
        
        return { x: 0, y: 0 };
    }

    update() {
        // 寻找目标位置
        const seekForce = this.seek(this.target);
        this.vx += seekForce.x;
        this.vy += seekForce.y;
        
        // 鼠标排斥
        if (mouse.x !== null && mouse.y !== null) {
            const fleeForce = this.flee(mouse);
            this.vx += fleeForce.x;
            this.vy += fleeForce.y;
        }
        
        // 限制速度
        const speed = Math.sqrt(this.vx * this.vx + this.vy * this.vy);
        if (speed > this.maxSpeed) {
            this.vx = (this.vx / speed) * this.maxSpeed;
            this.vy = (this.vy / speed) * this.maxSpeed;
        }
        
        // 更新位置
        this.x += this.vx;
        this.y += this.vy;
        
        // 添加阻尼，让移动更平滑
        this.vx *= 0.95;
        this.vy *= 0.95;
    }

    draw() {
        // 根据主题动态改变粒子颜色
        const isDark = document.body.getAttribute('data-theme') === 'dark';
        const color = isDark ? '102, 126, 234' : '255, 255, 255';
        
        ctx.fillStyle = `rgba(${color}, ${this.opacity})`;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
    }
}

// 创建粒子群
const boids = [];
for (let i = 0; i < textPoints.length; i++) {
    // 为每个目标点创建一个粒子
    if (Math.random() > 0.7) { // 30%的采样率，避免太密集
        boids.push(new Boid(textPoints[i]));
    }
}

// 动画循环
function animateBoids() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制鼠标光效
    if (mouse.x !== null && mouse.y !== null) {
        // 外圈光晕
        const gradient = ctx.createRadialGradient(mouse.x, mouse.y, 0, mouse.x, mouse.y, mouse.radius);
        const isDark = document.body.getAttribute('data-theme') === 'dark';
        const color = isDark ? '102, 126, 234' : '255, 255, 255';
        gradient.addColorStop(0, `rgba(${color}, 0.15)`);
        gradient.addColorStop(0.5, `rgba(${color}, 0.05)`);
        gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
        
        ctx.fillStyle = gradient;
        ctx.beginPath();
        ctx.arc(mouse.x, mouse.y, mouse.radius, 0, Math.PI * 2);
        ctx.fill();
        
        // 内圈高亮
        const innerGradient = ctx.createRadialGradient(mouse.x, mouse.y, 0, mouse.x, mouse.y, 30);
        innerGradient.addColorStop(0, `rgba(${color}, 0.4)`);
        innerGradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
        
        ctx.fillStyle = innerGradient;
        ctx.beginPath();
        ctx.arc(mouse.x, mouse.y, 30, 0, Math.PI * 2);
        ctx.fill();
    }
    
    // 更新和绘制粒子（不连接）
    boids.forEach(boid => {
        boid.update();
        boid.draw();
    });
    
    requestAnimationFrame(animateBoids);
}

animateBoids();

// 窗口大小改变时重新设置画布
window.addEventListener('resize', () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    
    // 重新生成目标点
    const newTextPoints = generateTextPoints();
    boids.forEach((boid, index) => {
        if (newTextPoints[index]) {
            boid.target = newTextPoints[index];
        }
    });
});

// ==================== 3D Tilt 效果 ====================
const profileCard = document.getElementById('profileCard');

// 删除原有的鼠标移动效果
// profileCard.addEventListener('mousemove', ...) - 已删除

profileCard.addEventListener('mouseleave', () => {
    profileCard.style.transform = '';
});

// ==================== 打字机效果 ====================
const typewriterElement = document.getElementById('typewriter');
let textIndex = 0;
let charIndex = 0;
let isDeleting = false;
let typeSpeed = 100;

function typeWriter() {
    const currentText = typewriterTexts[textIndex];
    
    if (isDeleting) {
        typewriterElement.textContent = currentText.substring(0, charIndex - 1);
        charIndex--;
        typeSpeed = 50;
    } else {
        typewriterElement.textContent = currentText.substring(0, charIndex + 1);
        charIndex++;
        typeSpeed = 100;
    }
    
    if (!isDeleting && charIndex === currentText.length) {
        typeSpeed = 2000; // 暂停
        isDeleting = true;
    } else if (isDeleting && charIndex === 0) {
        isDeleting = false;
        textIndex = (textIndex + 1) % typewriterTexts.length;
        typeSpeed = 500;
    }
    
    setTimeout(typeWriter, typeSpeed);
}

// 启动打字机效果
setTimeout(typeWriter, 1000);

// ==================== 社交按钮波纹效果 ====================
const socialButtons = document.querySelectorAll('.social-btn');

socialButtons.forEach(button => {
    button.addEventListener('click', function(e) {
        const ripple = this.querySelector('.ripple');
        const rect = this.getBoundingClientRect();
        const size = Math.max(rect.width, rect.height);
        const x = e.clientX - rect.left - size / 2;
        const y = e.clientY - rect.top - size / 2;
        
        ripple.style.width = ripple.style.height = size + 'px';
        ripple.style.left = x + 'px';
        ripple.style.top = y + 'px';
        ripple.style.transform = 'scale(0)';
        
        // 触发动画
        ripple.style.animation = 'none';
        setTimeout(() => {
            ripple.style.animation = 'rippleEffect 0.6s ease-out';
        }, 10);
    });
});

// ==================== 下载 vCard ====================
const downloadVCardBtn = document.getElementById('downloadVCard');

downloadVCardBtn.addEventListener('click', () => {
    const vcard = `BEGIN:VCARD
VERSION:3.0
FN:${personalInfo.name}
TITLE:${personalInfo.title}
EMAIL:${personalInfo.email}
TEL:${personalInfo.phone}
ADR:;;${personalInfo.location};;;;
URL:${personalInfo.website}
NOTE:GitHub: ${personalInfo.github}\\nLinkedIn: ${personalInfo.linkedin}
END:VCARD`;

    const blob = new Blob([vcard], { type: 'text/vcard' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `${personalInfo.name.replace(/\s/g, '_')}.vcf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    // 按钮反馈
    showNotification('名片已下载！');
});

// ==================== 分享功能 ====================
const shareCardBtn = document.getElementById('shareCard');

shareCardBtn.addEventListener('click', async () => {
    const shareData = {
        title: personalInfo.name,
        text: `${personalInfo.name} - ${personalInfo.title}`,
        url: personalInfo.website
    };
    
    try {
        if (navigator.share) {
            await navigator.share(shareData);
            showNotification('分享成功！');
        } else {
            // 复制链接到剪贴板
            await navigator.clipboard.writeText(personalInfo.website);
            showNotification('链接已复制到剪贴板！');
        }
    } catch (err) {
        if (err.name !== 'AbortError') {
            showNotification('分享失败，请重试');
        }
    }
});

// ==================== 通知提示 ====================
function showNotification(message) {
    const notification = document.createElement('div');
    notification.textContent = message;
    notification.style.cssText = `
        position: fixed;
        top: 100px;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(102, 126, 234, 0.9);
        color: white;
        padding: 15px 30px;
        border-radius: 25px;
        font-size: 1rem;
        z-index: 10000;
        backdrop-filter: blur(10px);
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
        animation: slideDown 0.3s ease-out;
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.animation = 'slideUp 0.3s ease-out';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 2000);
}

// 添加通知动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideDown {
        from {
            opacity: 0;
            transform: translateX(-50%) translateY(-20px);
        }
        to {
            opacity: 1;
            transform: translateX(-50%) translateY(0);
        }
    }
    
    @keyframes slideUp {
        from {
            opacity: 1;
            transform: translateX(-50%) translateY(0);
        }
        to {
            opacity: 0;
            transform: translateX(-50%) translateY(-20px);
        }
    }
`;
document.head.appendChild(style);

// ==================== 头像交互效果 ====================
const avatar = document.getElementById('avatar');

avatar.addEventListener('click', () => {
    avatar.style.animation = 'none';
    setTimeout(() => {
        avatar.style.animation = 'avatarBounce 0.6s ease';
    }, 10);
});

// 添加头像动画
const avatarStyle = document.createElement('style');
avatarStyle.textContent = `
    @keyframes avatarBounce {
        0%, 100% { transform: translate(-50%, -50%) scale(1); }
        25% { transform: translate(-50%, -50%) scale(0.95); }
        50% { transform: translate(-50%, -50%) scale(1.05); }
        75% { transform: translate(-50%, -50%) scale(0.98); }
    }
`;
document.head.appendChild(avatarStyle);

// ==================== 页面加载动画 ====================
window.addEventListener('load', () => {
    document.body.style.opacity = '0';
    setTimeout(() => {
        document.body.style.transition = 'opacity 0.5s ease';
        document.body.style.opacity = '1';
    }, 100);
});
